package com.steven.im.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aigestudio.wheelpicker.WheelPicker;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.makeramen.roundedimageview.RoundedImageView;
import com.steven.im.R;
import com.steven.im.base.BaseActivity;
import com.steven.im.base.Constant;
import com.steven.im.utils.BitmapOption;
import com.steven.im.utils.FileUtils;
import com.steven.im.utils.PermissionUtils;
import com.steven.im.utils.ScreenUtil;
import com.steven.im.utils.TitleBuilder;
import com.steven.im.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BottomDialog;

import static com.steven.im.base.Constant.EDIT_NICKNAME;
import static com.steven.im.base.Constant.PICK_PHOTO_CODE;
import static com.steven.im.base.Constant.TAKE_PHOTO_CODE;

public class IMMineInfoActivity extends BaseActivity {
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;

    @BindView(R.id.wheelPicker)
    WheelPicker wheelPicker;
    @BindView(R.id.ll_select)
    LinearLayout ll_select;
    @BindView(R.id.vObscuration)
    View vObscuration;
    @BindView(R.id.rl_content)
    RelativeLayout rl_content;
    @BindView(R.id.tv_sex)
    TextView tv_sex;
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.im_ivHead)
    RoundedImageView roundedImageView;
    private List<String> sexList;
    private String sex = "男";

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void setListen() {
        rl_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                vObscuration.setVisibility(View.GONE);
                ll_select.setVisibility(View.GONE);
                return false;
            }
        });
        wheelPicker.setOnWheelChangeListener(new WheelPicker.OnWheelChangeListener() {
            @Override
            public void onWheelScrolled(int offset) {

            }

            @Override
            public void onWheelSelected(int position) {
                tv_sex.setText(sexList.get(position));
                sex = sexList.get(position);
            }

            @Override
            public void onWheelScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void setTitleBarColor() {
        ivTitleRight.setVisibility(View.GONE);
        new TitleBuilder(this).setTitleText(getString(R.string.mineInfo))
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_im_mineinfo;
    }

    @Override
    public void initView() {
    }

    @Override
    public void initData() {
        sexList = new ArrayList<>();
        sexList.add("男");
        sexList.add("女");
    }

    @OnClick({R.id.rl_sex, R.id.tv_back, R.id.tv_done, R.id.rl_changePhoto, R.id.rl_nickname})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.rl_sex://性别
                vObscuration.setVisibility(View.VISIBLE);
                ll_select.setVisibility(View.VISIBLE);
                wheelPicker.setData(sexList);
                break;
            case R.id.tv_back://关闭选择框
                vObscuration.setVisibility(View.GONE);
                ll_select.setVisibility(View.GONE);
                break;
            case R.id.tv_done://修改完成
                vObscuration.setVisibility(View.GONE);
                ll_select.setVisibility(View.GONE);
                break;
            case R.id.rl_changePhoto://修改图像
                showSelectDialog();
                break;
            case R.id.rl_nickname://修改昵称
                startActivityForResult(new Intent(this, IMChangeNikeNameActivity.class)
                        .putExtra("nickname", "大张大"), EDIT_NICKNAME);
                break;
        }
    }

    /**
     * 选择照片弹窗
     */
    private void showSelectDialog() {
        final BottomDialog bottomDialog;
        bottomDialog = BottomDialog.create(this.getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                //照相
                v.findViewById(R.id.tv_takephoto).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (PermissionUtils.getInstance().checkPermission(IMMineInfoActivity.this,
                                Manifest.permission.CAMERA)) {
                            File myhead = new File(Constant.DIR_INFO.APP_DIR + "/head.jpg");
                            Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri uri = FileProvider.getUriForFile(IMMineInfoActivity.this,
                                    getPackageName() + ".provider", myhead);
                            it.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                            startActivityForResult(it, PICK_PHOTO_CODE);
                        } else {
                            PermissionUtils.getInstance().showSystemPermissionsSettingDialog(IMMineInfoActivity.this);
                        }
                        bottomDialog.dismiss();
                    }
                });
                //选择照片
                v.findViewById(R.id.tv_selectphoto).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent it = new Intent(Intent.ACTION_PICK, null);
                        it.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        startActivityForResult(it, TAKE_PHOTO_CODE);
                        bottomDialog.dismiss();
                    }
                });

                //取消
                v.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomDialog.dismiss();
                    }
                });

            }
        }).setLayoutRes(R.layout.select_change_image)
                .setDimAmount(0.4f)            // Dialog window dim amount(can change window background color）, range：0 to 1，default is : 0.2f
                .setCancelOutside(true)     // click the external area whether is closed, default is : true
                .setTag("BottomDialog")     // setting the DialogFragment tag
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选择图片
        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
            if (data.getData() != null) {
                Log.i("路径", "路径为：" + FileUtils.getFilePath(this, data.getData()));
                ///storage/emulated/0/Pictures/Screenshots/Screenshot_20190123-214734.jpg
                File file = new File(FileUtils.getFilePath(this, data.getData()));
                if(file.exists()){
                    Bitmap bm = BitmapFactory.decodeFile(FileUtils.getFilePath(this, data.getData()));
                    roundedImageView.setImageBitmap(bm);
                }
                //上传图片
                if (FileUtils.getFilePath(this, data.getData()) != null) {
                    // TODO 上传服务器
                } else {
                    ToastUtil.showShort(this, "文件不存在");
                }
            }
        }

        //拍照
        if (requestCode == PICK_PHOTO_CODE && resultCode == RESULT_OK) {
            File temp = new File(Constant.DIR_INFO.APP_DIR + "/head.jpg");
            if (temp.exists()) {
                // TODO 上传服务器
                Bitmap bm = BitmapFactory.decodeFile(Constant.DIR_INFO.APP_DIR + "/head.jpg");
                roundedImageView.setImageBitmap(bm);
            } else {
                ToastUtil.showShort(this, "文件不存在");
            }
        }
        //修改昵称
        if (requestCode == EDIT_NICKNAME && resultCode == RESULT_OK) {
            assert data != null;
            String nickname = data.getStringExtra("nickname");
            tv_nickname.setText(nickname);
        }
    }

}
